package com.changgou.user.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.order.pojo.Task;
import com.changgou.user.config.RabbitMQConfig;
import com.changgou.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class AddPointListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitMQConfig.CG_BUYING_ADDPOINT)
    public void receiveMessage(String message) {
        System.out.println("用户服务接收到了任务消息");

        Task task = JSON.parseObject(message, Task.class);
        //对监听队列监听到的消息进行非空判断
        if (task == null || StringUtils.isNotEmpty(task.getRequestBody())) {
            return;
        }
        //当消息队列监听的任务不为空或者请求体不为空时,判断Redis中是否有该任务存在
        Object values = redisTemplate.boundValueOps(task.getId()).get();
        if (values == null) {
            return;
        }

        //更新用户积分

        int result = userService.updateUserPoints(task);
        if (result <= 0) {
            return;
        }
        //返回通知
        rabbitTemplate.convertAndSend(RabbitMQConfig.EX_BUYING_ADDPOINTUSER, RabbitMQConfig.CG_BUYING_FINISHADDPOINT_KEY, JSON.toJSONString(task));
        System.out.println("用户服务向完成添加积分队列添加了一条消息");
    }
}
